package coder812.User.controller;

import coder812.User.entity.User;
import coder812.User.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import static coder812.common.utils.SecurityUtils.*;

/**
 * Created by 来自北海的风 on 2017/8/12.
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private UserService userServiceImpl;

    @Autowired
    public LoginController(UserService userServiceImpl){
       this.userServiceImpl=userServiceImpl;
   }
     @RequestMapping
    public String loginTest() throws UnsupportedEncodingException, NoSuchAlgorithmException {
//         User user=new User();
//         user.setRealName("123456");
//         user.setUsername("laowang");
//         user.setPassword("123456");
        // userServiceImpl.insertUser(user);

        return "login";
    }
     @RequestMapping("/check")
     @ResponseBody  //POST模式下，使用@RequestBody绑定请求对象，Spring会帮你进行协议转换，将Json、Xml协议转换成你需要的对象。
    public String CheckPassword(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String userName = request.getParameter("username");
        String pwd = request.getParameter("password");
        System.out.println("userName="+userName);

        User user = userServiceImpl.selectByUsername("userName");
        // User user=userServiceImpl.findUserById(2);

        if (user!= null) {
            System.out.println("名字是："+user.getUsername());

            if (checkPassword(pwd,user.getPassword())) {
                request.getSession().setAttribute("userinfo",user);
                return "login_succ";

            }
        } else {
            System.out.println("这是密码错误");
            return "login_fail";
        }
     System.out.println("这是user=null");
        return "login_fail";
    }

}


